var multiparty = require('multiparty');
var fs = require('fs');
var mongoose = require('mongoose');
mongoose.Promise = global.Promise;
var connection = require("../../app_modules/dbAccess/mongoConfig.js");
var moment = require('moment');

//id:为objectid
exports.uploadFIle = function (id, inputFile, metadata) {
	var headerString = JSON.stringify(inputFile.headers, null, 2).replace("content-type", "content_type");
	var header = JSON.parse(headerString);
	var mygrid = {};
	mygrid.path = inputFile.path;
	mygrid.fileObj = {
		_id: id,
		filename: inputFile.originalFilename,
		mode: 'w',
		chunkSize: inputFile.size,
		content_type: header.content_type,
		root: 'my_files'
	}
	mygrid.fileObj.metadata = metadata;
	mygrid.fileObj.metadata.createDate = moment().format('YYYY-MM-DD HH:MM');

	exports.createGridfs(mygrid);
}




exports.createGridfs = function (mygrid) {
	var conn = mongoose.createConnection(connection.getConnectionString(""));
	var Grid = require('gridfs-stream');
	conn.once('open', function () {
		var gfs = Grid(conn.db, mongoose.mongo);
		var writestream = gfs.createWriteStream(mygrid.fileObj);
		fs.createReadStream(mygrid.path).pipe(writestream);
		fs.unlinkSync(mygrid.path);
	})
};


exports.getGridfs = function (id, res) {
	var writerStream = fs.createWriteStream('public/files/images/113333322.jpg');
	var conn = mongoose.createConnection(connection.getConnectionString(""));
	var Grid = require('gridfs-stream');
	conn.once('open', function () {
		var gfs = Grid(conn.db, mongoose.mongo);	
		var readstream = gfs.createReadStream({ _id: id, root: 'my_files' });
		readstream.pipe(writerStream);
		//readstream.pipe(res);
		//获取其中的一项的信息
		gfs.findOne({ _id: id, root: 'my_files' }, function (err, file) { console.log(file) });

		res.send("h");
	})
};

exports.removeGridfs = function (id, res) {
	var conn = mongoose.createConnection(connection.getConnectionString(""));
	var Grid = require('gridfs-stream');
	conn.once('open', function () {
		var gfs = Grid(conn.db, mongoose.mongo);
		gfs.remove({ _id: id, root: "my_files" }, function (err) {
			console.log('success');
		});
	})
}

exports.gridfsExist = function (id, res) {
	var conn = mongoose.createConnection(connection.getConnectionString(""));
	var Grid = require('gridfs-stream');
	conn.once('open', function () {
		var gfs = Grid(conn.db, mongoose.mongo);
		gfs.exist({_id: id, root: 'my_files' }, function (err, found) {
			found ? console.log('File exists') : console.log('File does not exist');
		});
	})
}


exports.invokeProcData = function(MetaData,res) {  
	a={};
	a.user="chuangzi";
	a.age=26;
	MetaData=JSON.stringify(a);
	//MetaData="{name:'yeyu',age:25}";	
	var conn = mongoose.createConnection(connection.getConnectionString(""));
	conn.once('open', function () {
		var db=conn.db;
		//存储过程调用
		db.eval('DataPipe('+MetaData+')', function(err, result) { 
			if(err)
			{
				console.log('Error:'+ err);
				return;
			}			 
			else{				
			res.json(result);
			}
		});
	})

	
}